package com.xbd.auth.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.solon.service.impl.ServiceImpl;
import com.xbd.auth.entity.User;
import com.xbd.auth.exception.ApiException;
import com.xbd.auth.mapper.UserMapper;
import com.xbd.auth.service.IUserService;
import org.noear.solon.aspect.annotation.Service;
import org.noear.solon.core.handle.Context;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public boolean checkUser(Context context, String username, String password) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = baseMapper.selectOne(wrapper);
        if (user == null) {
            throw new ApiException("用户不存在");
        }
        boolean check = DigestUtil.bcryptCheck(password, user.getPassword());
        if (check) {
            context.sessionSet("userId", user.getId());
            context.sessionSet("username", user.getUsername());
            context.cookieSet("TOKEN", context.sessionState().sessionToken());
        }
        return check;
    }
}
